/*******************************************************************************
 * Includes
 ******************************************************************************/
#include "hc32f4a0.h"

/*******************************************************************************
 * Code
 ******************************************************************************/
/**
 * \brief 平台初始化
 */
void Wed_platform_init(void){
    int                     ret = 0;
    struct hc32f4a0_clk_pll pllh_cfg;

    /* 设置板级系统时钟 PLLH 240 MHz
     * Flash:         5 wait
     * SRAM_HS:       1 wait
     * SRAM1_2_3_4_B: 2 wait
     * PCLK0:         240 MHz
     * PCLK1:         120 MHz
     * PCLK2:         60 MHz
     * PCLK3:         60 MHz
     * PCLK4:         120 MHz
     * EXCLK:         120 MHz
     * HCLK:          240 MHz */
    /* 系统寄存器写使能 */
    sys_peripheral_we();
    /* 备份时钟寄存器值 */
    sys_clk_reg_backup();
    /* 设置外部晶振频率 */
    sys_clk_xtal_set(24000000);
    /* 设置系统时钟分配
     * PCLK0, HCLK  Max 240 MHz
     * PCLK1, PCLK4 Max 120 MHz
     * PCLK2, PCLK3 Max 60 MHz
     * EX BUS Max 120 MHz */
    ret = sys_clk_div_set(CLK_CATE_ALL,                                      \
                         (CLK_PCLK0_DIV1 | CLK_PCLK1_DIV2 | CLK_PCLK2_DIV4 | \
                          CLK_PCLK3_DIV4 | CLK_PCLK4_DIV2 | CLK_EXCLK_DIV2 | \
                          CLK_HCLK_DIV1));
    if (ret != 0) {
        while(1);
    }

    /* VCO = (8 /1)*120 = 960 MHz
     * VCO = (24/3)*120 = 960 MHz */
    pllh_cfg.pll_sta             = CLK_PLLH_ON;
    pllh_cfg.pll_cfg_r           = 0;
    pllh_cfg.pll_cfg_r_f.pll_m   = 3 - 1;
    pllh_cfg.pll_cfg_r_f.pll_n   = 120 - 1;
    pllh_cfg.pll_cfg_r_f.pll_p   = 4 - 1;
    pllh_cfg.pll_cfg_r_f.pll_q   = 4 - 1;
    pllh_cfg.pll_cfg_r_f.pll_r   = 4 - 1;
    pllh_cfg.pll_cfg_r_f.pll_src = CLK_PLLSRC_XTAL;

    /* 初始化 PLLH */
    ret = sys_clk_pllh_init(&pllh_cfg);
    if (ret != 0) {
        while(1);
    }
    /* 设置高速 SRAM 读写等待 1 周期 */
    ret = sram_wait_cycle_set(SRAM_SRAMH, SRAM_WAIT_CYCLE_1, SRAM_WAIT_CYCLE_1);
    if (ret != 0) {
        while(1);
    }
    /* 设置 SRAM 1,2,3,4 备份读写等待 2 周期 */
    ret = sram_wait_cycle_set((SRAM_SRAM123 | SRAM_SRAM4 | SRAM_SRAMB), SRAM_WAIT_CYCLE_2, SRAM_WAIT_CYCLE_2);
    if (ret != 0) {
        while(1);
    }
    /* 0-wait @ 40 MHz */
    ret = efm_wait_cycle_set(EFM_WAIT_CYCLE_5);
    if (ret != 0) {
        while(1);
    }
    /* 4 cycles for 200 ~ 250 MHz */
    ret = gpio_read_wait_cycle_set(GPIO_READ_WAIT_4);
    if (ret != 0) {
        while(1);
    }
    /* 设置时钟源 */
    sys_clk_src_set(CLK_SYSCLKSOURCE_PLLH);
    /* 系统寄存器写保护 */
    sys_peripheral_wp();


}
